﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data.Entity;
using LiUTrading.Models;
using LiUTrading.Helpers;

namespace LiUTrading.Controllers
{

    public class AdsController : Controller
    {
        AdRepository adRepository = new AdRepository();
        UserRepository userRepository = new UserRepository();
        //
        // GET: /Ads/

        public ActionResult Index(int page = 0)
        {
            const int pageSize = 10;
            var allAds = adRepository.FindAllAds();
            var paginateAllAds = new PaginatedList<Ad>(allAds, page, pageSize);
            return PartialView(paginateAllAds);
        }
        public ActionResult Details(int id)
        {
            Ad ad = adRepository.GetAd(id);
            if (ad == null)
            {
                return PartialView("NotFound");
            }
            else
            {
                return PartialView(ad);
            }

        }

        //Get : /Ads/Create
        [Authorize]
        public ActionResult Create()
        {

            User user = userRepository.GetUser(User.Identity.Name);
            Ad ad = new Ad()
            {
                UserId = user.UserId,
                DateTime = DateTime.Now,
                UserLiuId = user.LiuID
            };

            return PartialView(new AdFormViewModel(ad));
        }
        //POST;/Ads/Create
        [HttpPost, Authorize]
        public ActionResult Create(Ad ad)
        {
            if (ModelState.IsValid)
            {
                if (TryUpdateModel(ad))
                {
                    adRepository.Add(ad);
                    adRepository.Save();
                    return Json(new { success = true });
                    //return RedirectToAction("Details", new { id = ad.AdId });
                }
            }
            return PartialView(new AdFormViewModel(ad));
        }

        //Get: Ads/Edit/
        [Authorize]
        public ActionResult Edit(int id)
        {
            Ad ad = adRepository.GetAd(id);
            return PartialView(new AdFormViewModel(ad));
        }

        //Post: /Ads/Edit/
        [HttpPost, Authorize]
        public ActionResult Edit(int id, FormCollection formValues)
        {
            Ad ad = adRepository.GetAd(id);
            if (ModelState.IsValid)
            {
                UpdateModel(ad, "Ad");
                adRepository.Save();
                return Json(new { success = true });
                //return RedirectToAction("Details", new { id = ad.AdId });

            }
            return PartialView(new AdFormViewModel(ad));
        }

        // GET:/Ads/Delete
        public ActionResult Delete(int id)
        {
            Ad ad = adRepository.GetAd(id);
            if (ad == null)
            {
                return PartialView("NotFound");
            }
            else
            {
                return PartialView(ad);
            }
        }

        // POST: /Ads/Delete
        [HttpPost]
        public ActionResult DeleteConfirm(int id, string confirmButton)
        {
            Ad ad = adRepository.GetAd(id);
            if (ad == null)
            {
                return PartialView("NotFound");
            }
            else
            {
                adRepository.Delete(ad);
                adRepository.Save();
                return Json(new { success = true });
            }

        }

        //GET /Ads/UserSpecific
        [Authorize]
        public ActionResult MyAds()
        {

            User user = userRepository.GetUser(User.Identity.Name);

            if (user == null)
            {
                return View("NotFound");
            }
            else
            {
                var userAds = adRepository.FindUsersAds(user.UserId);
                return PartialView(userAds);
            }
        }

        public PartialViewResult LatestAds()
        {
            const int listSize = 10;
            var allAds = adRepository.FindAllAds();
            var latestAdsList = new List<Ad>(allAds.Take(listSize));
            return PartialView(latestAdsList);
        }

        public bool OwnedBy(string userName)
        {
            if (userName == User.Identity.Name)
            {
                return true;
            }
            return false;
        }

        public PartialViewResult ContactInformation(string userLiuID)
        {
            User user = userRepository.GetUser(userLiuID);
            if (user == null)
            {
                return PartialView("NotFound");
            }
            else
            {
                
                return PartialView(user);
            }
        }

        public JsonResult GetJson()
        {
            var allAds = adRepository.FindAllAds();
            IEnumerable<Ad> filteredAds = allAds;
            if (!string.IsNullOrEmpty(Request["sSearch"]))
            {
                string searchString = Request["sSearch"];
                filteredAds = adRepository.FindAllAds().Where(a => a.Category.Contains(searchString) || a.Title.Contains(searchString) || a.InfoText.Contains(searchString));
            }

            var sortColumnIndex = Convert.ToInt32(Request["iSortCol_0"]);
            Func<Ad, object> orderingFunction = a =>
            {
                if (sortColumnIndex == 1)
                {
                    return a.DateTime;
                }
                else if (sortColumnIndex == 2) { return a.Title;  }
                else if (
                sortColumnIndex == 3) { return a.Category; }
                else if (
                sortColumnIndex == 4) { return a.Price; }
                else { return a.AdId; }
            };
            var sortDirection = Request["sSortDir_0"];
            if (sortDirection == "asc")
            {
                filteredAds = filteredAds.OrderBy(orderingFunction);
            }
            else
            {
                filteredAds = filteredAds.OrderByDescending(orderingFunction);
            }

            var displayedAds = filteredAds
                                .Skip(Convert.ToInt32(Request["iDisplayStart"]))
                                .Take(Convert.ToInt32(Request["iDisplayLength"]));
            var result = from a in displayedAds select new[] { Convert.ToString(a.AdId), Convert.ToString(a.DateTime), a.Title, a.Category, Convert.ToString(a.Price) };
            return Json(new
            {
                sEcho = Request.Params["sEcho"],
                iTotalRecords = allAds.Count(),
                iTotalDisplayRecords = filteredAds.Count(),
                aaData = result
            }, JsonRequestBehavior.AllowGet);
        }
    }
}
